package com.library.management.service.borrow.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.library.management.domain.book.Book;
import com.library.management.domain.borrow.Borrow;
import com.library.management.mapper.borrow.BorrowMapper;
import com.library.management.service.book.BookService;
import com.library.management.service.borrow.BorrowService;
import com.library.management.domain.borrow.vo.BorrowVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class BorrowServiceImpl extends ServiceImpl<BorrowMapper, Borrow> implements BorrowService {
    
    @Autowired
    private BookService bookService;
    
    @Override
    public Page<BorrowVO> getBorrowPage(Integer page, Integer size, String keyword, Integer status, Long userId) {
        Page<BorrowVO> pageParam = new Page<>(page, size);
        return this.baseMapper.selectBorrowPage(pageParam, keyword, status, userId);
    }
    
    @Override
    public Page<BorrowVO> getBorrowByUserId(Long userId, Integer page, Integer size) {
        Page<BorrowVO> pageParam = new Page<>(page, size);
        return this.baseMapper.selectBorrowByUserId(pageParam, userId);
    }
    
    @Override
    @Transactional
    public boolean returnBook(Long borrowId, String remarks) {
        Borrow borrow = this.getById(borrowId);
        if (borrow == null) {
            throw new RuntimeException("借阅记录不存在");
        }
        if (borrow.getStatus() == 2) {
            throw new RuntimeException("图书已归还");
        }
        
        // 更新借阅记录
        borrow.setActualReturnDate(LocalDateTime.now());
        borrow.setStatus(2); // 已归还
        if (remarks != null) {
            borrow.setRemarks(remarks);
        }
        
        boolean success = this.updateById(borrow);
        if (success) {
            // 更新图书可借册数
            Book book = bookService.getById(borrow.getBookId());
            if (book != null) {
                book.setAvailableCopies(book.getAvailableCopies() + 1);
                bookService.updateById(book);
            }
        }
        
        return success;
    }
    
    @Override
    public boolean renewBook(Long borrowId, Integer renewDays) {
        Borrow borrow = this.getById(borrowId);
        if (borrow == null) {
            throw new RuntimeException("借阅记录不存在");
        }
        if (borrow.getStatus() != 1) {
            throw new RuntimeException("只能续借借阅中的图书");
        }
        
        // 更新应还日期
        borrow.setReturnDate(borrow.getReturnDate().plusDays(renewDays));
        borrow.setRemarks(borrow.getRemarks() + " (续借" + renewDays + "天)");
        
        return this.updateById(borrow);
    }
    
    @Override
    @Transactional
    public boolean borrowBook(Long userId, Long bookId, Integer borrowDays, String remarks) {
        // 检查图书是否存在且有库存
        Book book = bookService.getById(bookId);
        if (book == null) {
            throw new RuntimeException("图书不存在");
        }
        if (book.getAvailableCopies() <= 0) {
            throw new RuntimeException("图书库存不足");
        }
        if (book.getStatus() != 1) {
            throw new RuntimeException("图书已下架");
        }
        
        // 创建借阅记录
        Borrow borrow = new Borrow();
        borrow.setUserId(userId);
        borrow.setBookId(bookId);
        borrow.setBorrowDate(LocalDateTime.now());
        borrow.setReturnDate(LocalDateTime.now().plusDays(borrowDays));
        borrow.setStatus(1); // 借阅中
        borrow.setRemarks(remarks);
        
        boolean success = this.save(borrow);
        if (success) {
            // 更新图书可借册数
            book.setAvailableCopies(book.getAvailableCopies() - 1);
            bookService.updateById(book);
        }
        
        return success;
    }
    
    @Override
    public void updateBorrowStatus() {
        // 处理逾期图书
        LocalDateTime now = LocalDateTime.now();
        
        // 查询所有借阅中且已过期的记录
        this.lambdaUpdate()
            .eq(Borrow::getStatus, 1)
            .lt(Borrow::getReturnDate, now)
            .set(Borrow::getStatus, 3) // 设置为逾期
            .update();
    }
    
   
} 